import uuid

from fastapi import HTTPException
from sqlalchemy.orm import Session

from api.model.knowledgebase_item_model import KnowledgebaseItem
from api.model.knowledgebase_model import Knowledgebase
from api.utils.session import with_session
from api.vo.form.knowledge_form import KnowledgebaseForm
from api.vo.query.knowledgebase_item_query import KnowledgebaseItemQuery
from api.vo.query.knowledgebase_query import KnowledgebaseQuery
from api.vo.value.knowledgebase_item_value import KnowledgebaseItemValue
from api.vo.value.knowledgebase_value import KnowledgebaseValue


@with_session
def add(session: Session, knowledgeItem: KnowledgebaseItem):
    session.add(knowledgeItem)
    return knowledgeItem

@with_session
def delete(session: Session, idList: list):
    for id in idList:
        knowledge_item = session.get(KnowledgebaseItem, id)
        if not knowledge_item:
            raise HTTPException(status_code=404, detail=f"id={id}的文件不存在")
        session.delete(knowledge_item)
    return idList

@with_session
def update_status(session: Session, idList: list, status: str):
    for id in idList:
        knowledge_item = session.get(KnowledgebaseItem, id)
        if not knowledge_item:
            raise HTTPException(status_code=404, detail=f"id={id}的文件不存在")
        knowledge_item.status = status
        session.merge(knowledge_item)
    return idList


@with_session
def list(session: Session, knowledgebaseItemQuery: KnowledgebaseItemQuery):
    query = session.query(KnowledgebaseItem)
    if knowledgebaseItemQuery.kb_id:
        query = query.filter(KnowledgebaseItem.kb_id == knowledgebaseItemQuery.kb_id)
    query = query.order_by(KnowledgebaseItem.create_date.desc()).limit(knowledgebaseItemQuery.rows).offset((knowledgebaseItemQuery.page - 1) * knowledgebaseItemQuery.rows)
    knowledgebase_items = query.all()
    count = query.count()
    if not knowledgebase_items:
        return [], 0
    list = [
        KnowledgebaseItemValue(
            id = el.id,
            name=el.name,
            parse=el.parser_id,
            createdTime=el.create_date.strftime("%Y-%m-%d %H:%M:%S"),
            chunk_size=el.chunk_num,
            status=el.status,
            run=el.run
        ) for el in knowledgebase_items
    ]
    return list, count
